package com.mishow.utils;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.mishow.bean.ScanCodeBean;
import com.mishow.log.MyLog;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningTaskInfo;
import android.content.ClipData;
import android.content.ContentResolver;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.net.DhcpInfo;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Environment;
import android.os.StatFs;
import android.provider.Settings;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.Base64;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.GridView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.Toast;

/**
 * 
 * 作者：wei.miao<br/>
 * 描述：系统工具类
 */
public class AndroidUtil {

	/**
	 * 
	 * 获取安装包信息
	 * 
	 * @param context
	 *            上下文
	 * @param packageName
	 *            包名
	 */
	public static PackageInfo getPackageInfo(Context context, String packageName) {
		List<PackageInfo> installedPackageList = context.getPackageManager().getInstalledPackages(
				PackageManager.GET_UNINSTALLED_PACKAGES);
		if (installedPackageList == null) {
			return null;
		}

		for (PackageInfo packageInfo : installedPackageList) {
			if ((null != packageInfo) && (null != packageInfo.packageName)
					&& packageInfo.packageName.equals(packageName)) {
				return packageInfo;
			}
		}

		return null;
	}

	/**
	 * 获取软件版本号
	 * 
	 * @param context
	 * @return 获取应用版本号
	 */
	public static int getVersionCode(Context context) {
		return getPackageInfo(context, context.getPackageName()).versionCode;
	}

	/**
	 * 获取应用版本名
	 * 
	 * @param context
	 * @return 应用的版本名称
	 */
	public static String getVersionName(Context context) {
		return getPackageInfo(context, context.getPackageName()).versionName;
	}

	/**
	 * 检测GPS是否开启
	 * 
	 * @param context
	 * @return
	 */
	public static boolean isGpsEnable(Context context) {
		LocationManager locationManager = ((LocationManager) context.getSystemService(Context.LOCATION_SERVICE));
		return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
	}

	/**
	 * 判断网络是否可用
	 * 
	 * @param mContext
	 *            上下文对象
	 * @return 是否存在可用的网络
	 */
	public static boolean isNetworkAvailable(Context mContext) {
		boolean isAvailable = false;
		final ConnectivityManager cm = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
		if (null != cm) {
			final NetworkInfo[] netinfo = cm.getAllNetworkInfo();
			if (null != netinfo) {
				for (int i = 0; i < netinfo.length; i++) {
					if (netinfo[i].isConnected()) {
						isAvailable = true;
					}
				}
			}
		}
		return isAvailable;
	}

	/**
	 * 
	 * 判断当前网络是否为wifi
	 * 
	 * @param mContext
	 *            上下文
	 * @return boolean 网络为wifi返回真
	 */
	public static boolean isWifi(Context mContext) {
		ConnectivityManager connectivityManager = (ConnectivityManager) mContext
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo activeNetInfo = connectivityManager.getActiveNetworkInfo();
		if (activeNetInfo != null && activeNetInfo.getType() == ConnectivityManager.TYPE_WIFI) {
			return true;
		}
		return false;
	}

	/**
	 * 检测手机号码格式
	 * 
	 * @param mobiles
	 *            手机号
	 * @return 是否为手机号
	 */
	public static boolean isMobileNO(String mobiles) {
		if (TextUtils.isEmpty(mobiles)) {
			return false;
		}
		Pattern p = Pattern.compile("^((13[0-9])|(14[0-9])|(15[0-9])|(18[0-9])|(17[0-9]))\\d{8}$");
		Matcher m = p.matcher(mobiles);

		return m.matches();
	}

	
	/**
	 * Date类型时间格式化
	 */
	public static String convertToTime(Date createDate) {
		String processCreate = "";
		SimpleDateFormat currentFormat;

		if (createDate != null) {

			currentFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
			processCreate = currentFormat.format(createDate);

		}
		return processCreate;
	}
	
	/**
	 * String类型时间格式化
	 */
	public static String convertToTime(String time) {
		
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
		Date date = null;  
        try {  
            date = df.parse(time);   
        } catch (ParseException e) {  
            e.printStackTrace();  
        }  
        date = java.sql.Date.valueOf(time);  
                                              
        return date.toString();  
	}
	/**
	 * long类型时间格式化
	 */
	public static String convertToTime(long time) {
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
		Date date = new Date(time);
		return df.format(date);
	}

	/**
	 * long类型时间格式化
	 */
	public static String convertToTime(long time, String pattern) {
		SimpleDateFormat df = new SimpleDateFormat(pattern);
		Date date = new Date(time);
		return df.format(date);
	}

	/**
	 * 判定SD卡是否挂载
	 */
	public static boolean checkSdcardMounted() {
		return android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED);
	}

	/*
	 * 截取URL文件地址
	 */
	public static String getDownloadImgOrAudioName(String url) {
		if (url == null) {
			return url;
		}

		String[] urlArray = url.split("/");
		return urlArray[urlArray.length - 1];
	}

	/*
	 * 设置录音长度
	 */
	public static long setAudioLength(long audioSize, long max, long min) {
		if (audioSize <= 1) {
			return min;
		} else if (audioSize >= 60) {
			return max;
		}

		return ((max - min) * audioSize) / 59 + min;
	}

	/*
	 * 截取URL地址路径
	 */
	public static String getDownloadImgOrAudioURL(String url) {
		if (url == null) {
			return url;
		}

		if (url.startsWith("http") || url.startsWith("https")) {
			String[] urlArray = url.split("/");
			return "/" + url.substring(url.indexOf(urlArray[3]));
		}

		return url;
	}

	/*
	 * 关闭软键盘
	 */
	public static void closeKeyboard(Activity activity) {
		final View vInput = activity.getWindow().peekDecorView();

		if (vInput != null && vInput.getWindowToken() != null) {
			InputMethodManager imm = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
			imm.hideSoftInputFromWindow(vInput.getWindowToken(), 0);
		}
	}

	// 从min图片获取全图路径
	public static String getBigPathFromThumb(String thumbImg) {
		if (TextUtils.isEmpty(thumbImg)) {
			return thumbImg;
		}

		if (thumbImg.contains("_MIN")) {
			thumbImg = thumbImg.replace("_MIN", "");
		}

		return thumbImg;
	}

	// 将传入时间与当前时间进行对比，是否今天昨天
	public static String getTime(Date date) {
		String todySDF = "今天 HH:mm";
		String yesterDaySDF = "昨天 HH:mm";
		String otherSDF = "M月d日 HH:mm";
		SimpleDateFormat sfd = null;
		String time = "";
		Calendar dateCalendar = Calendar.getInstance();
		dateCalendar.setTime(date);
		Date now = new Date();
		Calendar targetCalendar = Calendar.getInstance();
		targetCalendar.setTime(now);
		targetCalendar.set(Calendar.HOUR_OF_DAY, 0);
		targetCalendar.set(Calendar.MINUTE, 0);
		if (dateCalendar.after(targetCalendar)) {
			sfd = new SimpleDateFormat(todySDF);
			time = sfd.format(date);
			return time;
		} else {
			targetCalendar.add(Calendar.DATE, -1);
			if (dateCalendar.after(targetCalendar)) {
				sfd = new SimpleDateFormat(yesterDaySDF);
				time = sfd.format(date);
				return time;
			}
		}
		sfd = new SimpleDateFormat(otherSDF);
		time = sfd.format(date);
		return time;
	}

	// 获取手机号码
	public static String getPhoneName(Context context) {
		String mobileNum = "";
		TelephonyManager phoneMgr = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
		if (phoneMgr == null) {
			return mobileNum;
		}
		mobileNum = phoneMgr.getLine1Number();
		if (TextUtils.isEmpty(mobileNum) || !mobileNum.startsWith("+86")) {
			return mobileNum;
		}
		// 去掉“+86”
		mobileNum = mobileNum.replace("+86", "");

		return mobileNum;
	}

	// ScrollView中嵌套Gridview， 代码中的columns，代表gridview 有columns列
	public static void setGridViewHeightBasedOnChildren(GridView gridView, int columns, int vSpace, int padding) {
		ListAdapter listAdapter = gridView.getAdapter();
		if (listAdapter == null) {
			// pre-condition
			return;
		}
		int totalHeight = 0;
		int hang = 0;
		if ((gridView.getCount() % columns) == 0) {

			hang = gridView.getCount() / columns;
		} else {
			hang = gridView.getCount() / columns + 1;
		}
		for (int i = 0; i < hang; i++) {
			View listItem = listAdapter.getView(i, null, gridView);
			listItem.measure(0, 0);
			totalHeight += listItem.getMeasuredHeight();
		}

		if (hang > 1) {
			totalHeight += vSpace * (hang - 1);
		}

		totalHeight += padding;
		ViewGroup.LayoutParams params = gridView.getLayoutParams();
		params.height = totalHeight;
		gridView.setLayoutParams(params);
	}

	// 在scrollView中嵌套ListView
	public static void setListViewHeightBasedOnChildren(ListView listView) {
		// 获取ListView对应的Adapter
		ListAdapter listAdapter = listView.getAdapter();
		if (listAdapter == null) {
			return;
		}

		int totalHeight = 0;
		for (int i = 0, len = listAdapter.getCount(); i < len; i++) { // listAdapter.getCount()返回数据项的数目
			View listItem = listAdapter.getView(i, null, listView);
			listItem.measure(0, 0); // 计算子项View 的宽高
			totalHeight += listItem.getMeasuredHeight(); // 统计所有子项的总高度
		}

		ViewGroup.LayoutParams params = listView.getLayoutParams();
		params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
		// listView.getDividerHeight()获取子项间分隔符占用的高度
		// params.height最后得到整个ListView完整显示需要的高度
		listView.setLayoutParams(params);
	}

	/**
	 * 将定位到的城市中的“市”去掉
	 */
	public static String getCityStr(String city) {
		if (TextUtils.isEmpty(city)) {
			return null;
		}
		if (city.endsWith("市")) {
			city = city.substring(0, city.length() - 1);
		}
		return city;
	}

	/*
	 * 判断是否有表情字符
	 */
	public static boolean checkSpecialCharacter(String c) {
		if (TextUtils.isEmpty(c)) {
			return false;
		}

		for (int i = 0; i < c.length(); i++) {
			Character mChar = c.charAt(i);

			byte[] b = mChar.toString().getBytes();

			try {
				if (b[0] == -16 && b[1] == -97 && b[2] == -104 || b[0] == 63) {
					return true;
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		return false;
	}

	/**
	 * 获取imei
	 * 
	 * @param context
	 *            上下文
	 * @return String imei号
	 */
	public static String getImei(Context context) {
		ContentResolver resolver = context.getContentResolver();
		String imei = Settings.System.getString(resolver, "device_imei");

		// 如果本地未保存，则获取手机设备ID
		if (TextUtils.isEmpty(imei)) {
			try {
				TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
				imei = tm.getDeviceId();
				Settings.System.putString(resolver, "device_imei", imei);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		// 如无法获取设备ID则生成一个UUID
		if (TextUtils.isEmpty(imei)) {
			imei = UUID.randomUUID().toString();
			imei = imei.replace("-", "");
			Settings.System.putString(resolver, "device_imei", imei);
		}
		return imei;
	}

	/**
	 * 获取图片完整路径 <br/>
	 * 
	 * @param [urlStr]-[服务器返回的图片地址] <br/>
	 * @param [width]-[图片宽] <br/>
	 * @param [height]-[图片高] <br/>
	 */
	public static String getImgUrl(String urlStr, int width, int height) {
		if (TextUtils.isEmpty(urlStr)) {
			return null;
		}

		if (urlStr.endsWith(".jpg") || urlStr.endsWith(".png")) {
			urlStr = urlStr.substring(0, urlStr.length() - 4);
		}

		return urlStr + "_" + width + "-" + height + ".jpg";
	}

	/**
	 * 获取图片的完整路径 <br/>
	 * 
	 * @param urlStr
	 * @return
	 */
	public static String getImgUrl(String urlStr) {
		if (TextUtils.isEmpty(urlStr)) {
			return null;
		}
		if (urlStr.endsWith(".jpg") || urlStr.endsWith(".png")) {
			return urlStr;
		}
		return urlStr + ".jpg";
	}

	/**
	 * 
	 * 将手机号中间四位隐藏 ，已****代替<br/>
	 * 
	 * @param [numStr]-[原手机号] <br/>
	 * @param [参数2]-[参数2说明] <br/>
	 */
	public static String getHideMobileNum(String numStr) {
		String numberString = "";
		if (TextUtils.isEmpty(numStr)) {
			return numberString;
		}

		// 判断是否为手机号
		if (!isMobileNO(numStr)) {
			return numStr;
		}

		if (numStr.length() == 11) {
			numberString = numStr.substring(0, 3) + "****" + numStr.substring(7, numStr.length());
		}
		return numberString;
	}

	/**
	 * 根据配送方式和配送金额返回展示数据
	 * 
	 * @param sendType
	 * @param payMoney
	 * @return
	 */
	public static String getPeiSongStr(int sendType, String payMoney, String limitMoney) {
		String peisongStr = "";
		switch (sendType) {
		case 1:// 1-满额包送，不满额需另付运费
			peisongStr = limitMoney + "元包送";
			break;
		case 2:// 2-固定配送金额
			peisongStr = "配送" + payMoney + "元";
			break;
		case 3:// 不提供配送服务
			peisongStr = "需自提";
			break;
		case 4:// XX元起送：不满额不提供送货上门，给运费也不干
			peisongStr = limitMoney + "元起送";
			break;
		default:
			break;
		}
		return peisongStr;
	}

	/**
	 * 根据状态显示相应的描述
	 * 
	 * @param status
	 * @return
	 */
	public static String getOrderStatusDes(String status, String sendType) {
		String des = "";
		if (TextUtils.isEmpty(status) || TextUtils.isEmpty(sendType)) {
			return des;
		}
		switch (Integer.parseInt(status)) {
		case 0:
			if (Integer.parseInt(sendType) == 3) {
				return "商家备货中";
			}
			return "待配送";
		case 1:
			if (Integer.parseInt(sendType) == 3) {
				return "待自提";
			}
			return "配送中";
		case 2:
		case 3:
			return "交易成功";
		case 4:
			return "订单关闭";
		default:
			break;
		}
		return des;

	}

	/**
	 * 判断Task的栈顶Activity是否为本程序的
	 * 
	 * @param context
	 *            环境
	 */
	public static boolean isOwnerActivity(Context context) {
		PackageInfo info;
		try {
			info = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
			return getTopActivity(context).equals(info.packageName);
		} catch (Exception e) {
			e.printStackTrace();
		}

		return false;
	}

	/**
	 * 获取Task的栈顶Activity所在的包名
	 * 
	 * @param context
	 *            环境
	 */
	public static String getTopActivity(Context context) {
		ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
		List<RunningTaskInfo> runningTaskInfos = manager.getRunningTasks(1);
		String packageName = null;
		if (null != runningTaskInfos) {
			packageName = runningTaskInfos.get(0).topActivity.getPackageName();
		}

		return packageName;
	}

	/**
	 * 检测某Activity是否在当前Task的栈顶
	 * 
	 * @param context
	 *            环境
	 * @param activity
	 *            Activity名
	 * @return boolean 在栈顶返回真
	 */
	public static boolean isTopActivty(Context context, String activity) {
		ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
		List<RunningTaskInfo> runningTaskInfos = manager.getRunningTasks(1);
		String nameTemp = null;
		if (null != runningTaskInfos) {
			nameTemp = runningTaskInfos.get(0).topActivity.getClassName();
			MyLog.d("com.rogrand.kkmy", "nameTemp = " + nameTemp);
		}

		if (null == nameTemp) {
			return false;
		}

		return nameTemp.equals(activity);
	}

	/**
	 * 获取咨询发布的时间差 <br/>
	 * 
	 * @param [publishTime]-[参数1说明] <br/>
	 * @param [参数2]-[参数2说明] <br/>
	 */
	public static String getConsultTime(long publishTime, long nowTime) {
		String timeStr = "";
		long time = nowTime - publishTime;
		if (time < 0) {
			timeStr = "";
		} else {
			// 分钟
			if (time < 60 * 1000l) {
				timeStr = "刚刚";
			} else if (time < 60 * 60 * 1000l) {
				long min = time / (60 * 1000l);
				timeStr = min + "分钟前";
			} else if (time < 24 * 60 * 60 * 1000l) {
				long hourCount = time / (60 * 60 * 1000l);
				timeStr = hourCount + "小时前";
			} else {
				timeStr = new SimpleDateFormat("MM月dd日", Locale.US).format(publishTime);
			}
		}
		return timeStr;
	}

	/** 判断两个时间戳是否在同一天 */
	public static boolean isSameDate(long publishTime, long nowTime) {
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd", Locale.US);
		Date pDate = new Date(publishTime);
		Date nowDate = new Date(nowTime);
		if (format.format(pDate).equals(format.format(nowDate))) {
			return true;
		}
		return false;
	}

	/**
	 * bitmap转为base64
	 * 
	 * @param bitmap
	 * @return
	 */
	public static String bitmapToBase64(Bitmap bitmap) {

		String result = null;
		ByteArrayOutputStream baos = null;
		try {
			if (bitmap != null) {
				baos = new ByteArrayOutputStream();
				bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);

				baos.flush();
				baos.close();

				byte[] bitmapBytes = baos.toByteArray();
				result = Base64.encodeToString(bitmapBytes, Base64.NO_WRAP);
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (baos != null) {
					baos.flush();
					baos.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return result;
	}

	/**
	 * base64转为bitmap
	 * 
	 * @param base64Data
	 * @return
	 */
	public static Bitmap base64ToBitmap(String base64Data) {
		byte[] bytes = Base64.decode(base64Data, Base64.NO_WRAP);
		return BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
	}

	/**
	 * 将A、B转换成对应的性别
	 * 
	 * @param sexTag
	 *            ：性别（A-女 B-男）
	 * @return 性别：男/女
	 */
	public static String getSexStr(String sexTag) {
		String sexStr = "";
		if ("A".equals(sexTag)) {
			sexStr = "女";
		} else {
			sexStr = "男";
		}
		return sexStr;
	}

	/**
	 * 指定的时间是否在今天范围之内
	 * 
	 * @param date
	 *            指定的时间
	 * @return true在今天范围之内，否则false
	 */
	public static boolean isInToday(long date) {
		boolean flag = false;
		Calendar c = Calendar.getInstance();
		c.setTimeInMillis(date);
		Calendar startTime = Calendar.getInstance();
		startTime.set(Calendar.HOUR_OF_DAY, 0);
		startTime.set(Calendar.MINUTE, 0);
		startTime.set(Calendar.SECOND, 0);
		Calendar endTime = Calendar.getInstance();
		endTime.set(Calendar.HOUR_OF_DAY, 23);
		endTime.set(Calendar.MINUTE, 59);
		endTime.set(Calendar.SECOND, 59);
		if (c.before(endTime) && c.after(startTime)) {
			flag = true;
		}
		return flag;
	}

	/**
	 * 获取url中的参数
	 * 
	 * @param url
	 * @return
	 */
	public static HashMap<String, String> getUrlParams(String url) {
		if (!url.contains("?")) {
			return null;
		}
		HashMap<String, String> paramsMap = new HashMap<String, String>();
		String[] codeParams = url.split("[?]");
		String[] param = null;
		if (codeParams[1].contains("&")) {
			String[] arrSplit = codeParams[1].split("[&]");
			for (String strSplit : arrSplit) {
				if (strSplit.contains("=")) {
					param = strSplit.split("[=]");
					paramsMap.put(param[0], param[1]);
				}
			}

		}
		return paramsMap;
	}

	/**
	 * 处理历史订单日期
	 * 
	 * @param createDate
	 * @return
	 */
	public static String processOrderHistoryDate(Date createDate) {

		String processCreate = "";
		SimpleDateFormat currentFormat;

		if (createDate != null) {

			currentFormat = new SimpleDateFormat("yyyy.MM.dd HH:mm", Locale.getDefault());
			processCreate = currentFormat.format(createDate);

		}
		return processCreate;

	}

	@SuppressLint("NewApi")
	@SuppressWarnings("deprecation")
	public static void copyToClipboard(Context context, String text) {
		if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.HONEYCOMB) {
			android.text.ClipboardManager cm = (android.text.ClipboardManager) context
					.getSystemService(Context.CLIPBOARD_SERVICE);
			cm.setText(text);
		} else {
			android.content.ClipboardManager cm = (android.content.ClipboardManager) context
					.getSystemService(Context.CLIPBOARD_SERVICE);
			cm.setPrimaryClip(ClipData.newPlainText(null, text));
		}
	}

	/**
	 * 将字符串中的"\"加上转义 在不同的系统中，路径的分隔符不同，故需要做出判断，并切换分隔符 ① java 把字符串中的反斜杠（\）替换成（\\）
	 * replaceAll里面用的是正则表达式，所以字符串转义一次，正则转义一次，所以一个斜扛要写4个，用 replaceAll( "\\\\ ",
	 * "\\\\\\\\"); ② java 把字符串中的反斜杠（/）替换成（\） replaceAll("/", "\\\\");
	 * 
	 * @param string
	 */
	public static String jsStrChange(String string) {
		if (TextUtils.isEmpty(string)) {
			return string;
		}
		if (string.contains("\\")) {
			string = string.replaceAll("\\\\", "\\\\\\\\");
		}
		return string;
	}

	/**
	 * 根据手机分辨率获取不同尺寸广告图片路径,当前提供的图片尺寸：240*480 480*800 640*960 720*1280 1080*1920
	 * 
	 * @param [urlStr]-[服务器返回的图片地址]
	 * @param [width]-[图片宽]
	 * @param [height]-[图片高]
	 */
	public static String getAdImgResolution(Context cx) {
		DisplayMetrics dm = new DisplayMetrics();
		dm = cx.getApplicationContext().getResources().getDisplayMetrics();
		int width = dm.widthPixels;
		String resolution = "7201280";
		List<String> rList = Arrays.asList(Constants.DEVICE_RESOLUTION);
		for (int i = 0; i < rList.size(); i++) {
			if (rList.get(i).startsWith(width + "")) {
				resolution = rList.get(i);
				break;
			}
		}
		return resolution;
	}

	/**
	 * 获取手机MAC地址
	 * @param ctx
	 * @return
	 */
	public static String getMacAddress(Context ctx) {
		String result = "";
		WifiManager wifiManager = (WifiManager) ctx.getSystemService(Context.WIFI_SERVICE);
		WifiInfo wifiInfo = wifiManager.getConnectionInfo();
		result = wifiInfo.getMacAddress();
		return result;
	}

	/**
	 * 获得当前网络类型
	 *
	 * @param mContext
	 *            上下文
	 * @return TYPE_MOBILE_CMNET:1 TYPE_MOBILE_CMWAP:2 TYPE_WIFI:3
	 *         TYPE_NO:0(未知类型)
	 */
	public static String getNetWorkType(Context mContext) {
		ConnectivityManager cm = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
		// 获得当前网络信息
		NetworkInfo ni = cm.getActiveNetworkInfo();
		if (ni != null && ni.isAvailable()) {
			int currentNetWork = ni.getType();
			if (currentNetWork == ConnectivityManager.TYPE_MOBILE) {
				if (ni.getExtraInfo() != null) {
					return ni.getExtraInfo();
				} else {
					return "非WIFI";
				}

			} else if (currentNetWork == ConnectivityManager.TYPE_WIFI) {
				return "WIFI";
			}
		}
		return "WIFI";
	}

	// 检查SD卡状态
	private boolean checkSDCard() {
		if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
			return true;
		}
		return false;
	}

	// 获取SD卡路径
	public static String getExternalStoragePath() {
		// 获取SdCard状态
		String state = android.os.Environment.getExternalStorageState();
		// 判断SdCard是否存在并且是可用的
		if (android.os.Environment.MEDIA_MOUNTED.equals(state)) {
			if (android.os.Environment.getExternalStorageDirectory().canWrite()) {
				return android.os.Environment.getExternalStorageDirectory().getPath();
			}
		}
		return null;
	}

	/**
	 * 获取存储卡的剩余容量，单位为字节
	 * 
	 * @param filePath
	 * @return availableSpare
	 */
	public static long getAvailableStore(String filePath) {
		// 取得sdcard文件路径
		StatFs statFs = new StatFs(filePath);
		// 获取block的SIZE
		long blocSize = statFs.getBlockSize();
		// 获取BLOCK数量
		// long totalBlocks = statFs.getBlockCount();
		// 可使用的Block的数量
		long availaBlock = statFs.getAvailableBlocks();
		// long total = totalBlocks * blocSize;
		long availableSpare = availaBlock * blocSize;
		return availableSpare;
	}

	/**
	 * 获取存储卡的状态，单位为字节
	 * 
	 * @param filePath
	 * @return availableSpare
	 */
	public static String getAvailableStoreString(String filePath) {
		// 取得sdcard文件路径
		StatFs statFs = new StatFs(filePath);
		// 获取block的SIZE
		long blocSize = statFs.getBlockSize();
		// 获取BLOCK数量
		long totalBlocks = statFs.getBlockCount();
		// 可使用的Block的数量
		long availaBlock = statFs.getAvailableBlocks();
		long total = totalBlocks * blocSize / 1000000;
		long availableSpare = availaBlock * blocSize / 1000000;
		
		float ava = availableSpare/1000f;
		float tot = total/1000f;
		
		return ava + "G/" + tot + "G";
	}

	public static String getDnsString(Context ctx) {
		DhcpInfo dhcpInfo = ((WifiManager) ctx.getSystemService("wifi")).getDhcpInfo();
		return intToIp(dhcpInfo.dns1);
	}

	public static String getGayWayString(Context ctx) {
		DhcpInfo dhcpInfo = ((WifiManager) ctx.getSystemService("wifi")).getDhcpInfo();
		return intToIp(dhcpInfo.gateway);
	}

	private static String intToIp(int paramInt) {
		return (paramInt & 0xFF) + "." + (0xFF & paramInt >> 8) + "." + (0xFF & paramInt >> 16) + "."
				+ (0xFF & paramInt >> 24);
	}

	public static String takeScreenShot(Activity activity){
        String filePath = FileUtil.getStructureDirs("screen_capture");
        String fileName = System.currentTimeMillis() + ".jpg";
        
        View rootView = activity.getWindow().getDecorView();
        rootView.setDrawingCacheEnabled(true);
        rootView.buildDrawingCache();
        Bitmap bitmap = rootView.getDrawingCache();
        File imagePath = new File(filePath+File.separator+fileName);
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(imagePath);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
            fos.flush();
        } catch (Exception e) {
        }finally {
            try{
                fos.close();
                bitmap.recycle();
                bitmap = null;
            }catch(Exception e){
            }
            rootView.destroyDrawingCache();
            rootView.setDrawingCacheEnabled(false);
        }
        Toast.makeText(activity, "截图已保存到"+filePath, Toast.LENGTH_SHORT).show();
        return filePath;
    }
	
	//---------------------------------------------------
	
	/**
	 * 日期对比
	 * @param time1 通告创建时间
	 * @param time2 当前时间
	 * @return
	 */
	private long timeContrast(String time1, String time2) {
		try {

			String strTime = proTime(time1,false);
			// 时间对比
			SimpleDateFormat objFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			Date d1 = objFormat.parse(strTime);
			Date d2 = objFormat.parse(time2);
			long d3 = d2.getTime() - d1.getTime();
			long abs = Math.abs((d3 / (1000 * 60)));
			long minute = abs;
			return minute;
		} catch (Exception e) {
			e.printStackTrace();
		}

		return 0;

	}
	
	/**
	 * 处理时间戳
	 * @param time
	 * @return
	 */
	private String proTime(String time,boolean isDisplayDate){
		
		StringBuilder sBuilder = new StringBuilder(time);
		String strdel = sBuilder.delete(sBuilder.lastIndexOf("."),
				sBuilder.lastIndexOf(".") + 2).toString();

		MyLog.e("MV", "strdel" + strdel);
		if (isDisplayDate) {
			
			SimpleDateFormat proFormat = new SimpleDateFormat("yyyy-MM-dd");
			try {
				Date parseTime = proFormat.parse(strdel);
				String tempTime = proFormat.format(parseTime);

				return tempTime;
				
			} catch (Exception e) {
				
				e.printStackTrace();
			}
			
		}
		
		return strdel;
	}
	
	/**
     * 获取生成二维码的字符串
     *
     * @return
     */
    public static String getScanCodeUrl(ScanCodeBean bean) {
        if (bean == null) {
            return null;
        }
        StringBuffer sb = new StringBuffer(CodeConstants.SCAN_CODE_STRING);
        sb.append("?");
        sb.append("codeType=" + bean.getCodeType());
        sb.append("&");
        sb.append("code=" + bean.getCode());
        return sb.toString();
    }
    /**
     * 获取当前包名
     * @param context
     * @param isCurrent
     * @return
     */
    public static String getCurrentPackageName(Context context, boolean isCurrent) {
        if (isCurrent) {
            return context.getPackageName();
        }
        return "com.mishow";
    }

    /**
	 * 扫一扫结果处理（店员邀请码、药店二维码、订单提货码）
	 * @param qCodeStr 扫码结果
	 * @return 
	 */
	public static ScanCodeBean scanResult(String qCodeStr) {
		if (TextUtils.isEmpty(qCodeStr)) {
			return null;
		}
		String code = "";
		int codeType = 0 ;
		
		if (qCodeStr.startsWith("KKMY_ORDER")) {
			//订单提货二维码
			codeType = CodeConstants.ORDER_CODE_TYPE;
			code = qCodeStr.substring("KKMY_ORDER".length(), qCodeStr.length());
		} else if (qCodeStr.startsWith("KKMY_DY")) {
			//店员邀请码
			codeType = CodeConstants.DY_CODE_TYPE;
			code = qCodeStr.substring("KKMY_DY".length(), qCodeStr.length());
		} else if (qCodeStr.startsWith("KKMY_YH")) {
			//用户邀请码
			codeType = CodeConstants.USER_CODE_TYPE;
			code = qCodeStr.substring("KKMY_YH".length(), qCodeStr.length());
		} else if (qCodeStr.startsWith(CodeConstants.SCAN_CODE_STRING + "?")) {
			HashMap<String, String> paramsMap = getUrlParams(qCodeStr);
			if (paramsMap != null) {
				if (paramsMap.containsKey("codeType")) {
					try {
						codeType = Integer.parseInt(paramsMap.get("codeType"));
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
				
				if (paramsMap.containsKey("code")) {
					code = paramsMap.get("code");
				}
			}
		}
		return new ScanCodeBean(codeType, code);
	}
}
